package com.xing.filter;

import cn.hutool.core.util.StrUtil;

import com.xing.DTO.UserDTO;
import com.xing.utils.JwtUtils;
import com.xing.utils.TokenUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/12/5 14:22
 */
@Component
@AllArgsConstructor
public class JwtAuthtienticationTokenFilter extends OncePerRequestFilter {
    private final JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException, ServletException {
        String token = TokenUtils.getAccesstoken(request);
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        UserDTO dto = jwtUtils.parseToken(token, UserDTO.class);
        if (dto == null) {
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println(123);
//        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        for (String perm : dto.getPower()) {
//            authorities.add(new SimpleGrantedAuthority(perm));
//        }
        Authentication authentication =
                new UsernamePasswordAuthenticationToken(dto, null, null);
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
        filterChain.doFilter(request, response);
    }
}
